<template>
    <el-dialog :title="form_title" :visible.sync="isShow" width="40%">
        <div class="dialog">
            <el-upload class="upload-demo" action="/api/report/upload" multiple :file-list="fileList" accept=".txt" :auto-upload="true" :on-change="handleFileUpload" :on-remove="handleRemove">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">选择算法测试文件</div>
            </el-upload>
            <div style="width: 100%; height: 70px"></div>
            <el-button v-for="item in tableMenu" :type="item.type" size="small" :icon="item.icon" @click="item.click">
                {{ item.text }}
            </el-button>
        </div>
    </el-dialog>
</template>
<script>
import { requestApi } from '@/requset/api'
import { deepClone } from '@/plugins/clone'
import { tableMenu } from './formConfig'
export default {
    data() {
        return {
            isShow: false,
            tableMenu: null,
            activeItem: null,
            fileList: [],
            val: null,
            fileValue: [],
        }
    },
    methods: {
        handleFileUpload(file) {
            let fileName = file.name
            // 其他处理逻辑
            const reader = new FileReader()
            reader.onload = (e) => {
                const fileContent = e.target.result
                const lines = fileContent.split('\n')
                let longestLineIndex = 0
                let longestLineLength = 0
                // 找到最长行的索引和长度
                lines.forEach((line, index) => {
                    const trimmedLine = line.trim()
                    if (trimmedLine.length > longestLineLength) {
                        longestLineLength = trimmedLine.length
                        longestLineIndex = index
                    }
                })
                this.fileValue.push({
                    fileName,
                    fs: lines[longestLineIndex - 4].trim(),
                    value: lines[longestLineIndex].trim(),
                    m_f: lines[longestLineIndex - 6].trim(),
                    fileContent,
                })
            }
            reader.readAsText(file.raw)
        },
        handleRemove() {
            this.fileValue = []
        },
        doOpen(e) {
            this.val = e
            this.isShow = true
        },
        sendMsg() {
            let obj = {
                succ: 0,
                err: 0,
            }
            let { value, topic, maker, model_name, id } = this.val
            let models = JSON.parse(value)
            // 生成 Promise 队列
            let create_time = this.dayjs().format('YYYY-MM-DD HH:mm:ss')
            let publishPromises = []
            models.forEach((e1) => {
                let { modelcode } = e1[e1.length - 1]
                if (modelcode) {
                    this.fileValue.forEach((e2) => {
                        let { fs, value, m_f, fileName, fileContent } = e2
                        let message = JSON.stringify({
                            modelcode,
                            maker,
                            fileName,
                            model_name,
                            create_time,
                            id,
                            test: true,
                            config: {
                                data: [
                                    {
                                        m_f,
                                        data_value: [value, fs],
                                        data_index: 'acc',
                                    },
                                ],
                            },
                            fileContent,
                        })
                        let publishPromise = new Promise((resolve, reject) => {
                            this.$mqtt.publish(topic, message, (err) => {
                                if (err) {
                                    obj.err++
                                    reject(err)
                                } else {
                                    obj.succ++
                                    resolve()
                                }
                            })
                        })
                        publishPromises.push(publishPromise)
                    })
                }
            })
            // 等待所有 Promise 完成
            Promise.all(publishPromises)
                .then(() => {
                    this.$message.success('成功下发' + obj.succ + '条')
                    this.isShow = false
                })
                .catch((err) => {
                    // 处理错误情况
                    this.$message.info('下发失败')
                })
        },
        updateMqtt() {
            this.$EventBus.$emit('undateMqtt')
        },
        selfins(e) {
            this.$refs.selfins.doOpen(e)
        },
    },
    created() {
        tableMenu[0].click = () => this.sendMsg()
        tableMenu[1].click = () => this.updateMqtt()

        this.tableMenu = tableMenu
    },
}
</script>

<style lang="less" scoped></style>
